<template>
  <view :class="`wd-picker-view ea-data-picker-view ${customClass}`" :style="customStyle">
    <view class="wd-picker-view__loading" v-if="loading">
      <wd-loading :color="loadingColor" />
    </view>
    <scroll-view :scroll-x="true" :scroll-y="true">
      <wd-cell-group border>
        <wd-cell
          v-for="(row, index) in formatColumns"
          :key="index"
          :title="row[labelKey]"
          :custom-class="`${row['disabled'] ? 'wd-picker-view-column__item--disabled' : ''}`"
          :custom-style="` ${row.color ? `color: ${row.color}` : ''}`"
          :clickable="!row['disabled']"
          center
          title-width="90%"
          @click="handleRowClick(row, index)"
        >
          <template #icon v-if="row.icon">
            <view v-if="row.icon" :class="row.icon" class="ea-data-picker-view-cell-icon" />
          </template>
          <view class="i-ic:baseline-check ea-data-picker-view-cell-icon" v-if="hasSelected(row)" />
        </wd-cell>
      </wd-cell-group>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { deepClone, isArray } from 'wot-design-uni/components/common/util';

  import { type ColumnItem, formatArray, type PickerViewExpose, pickerViewProps } from './types';

  defineOptions({
    name: 'ea-data-picker-view',
    options: {
      virtualHost: true,
      addGlobalClass: true,
      styleIsolation: 'shared',
    },
  });
  const props = defineProps(pickerViewProps);
  const emit = defineEmits(['change', 'click', 'update:modelValue']);

  /** 格式化后的列数据 */
  const formatColumns = ref<ColumnItem[]>([]);
  /** 选中的值 */
  const selectedValue = ref(props.modelValue || '');

  watchEffect(() => {
    selectedValue.value = props.modelValue || '';
  });

  watch(
    () => props.columns,
    (v) => {
      formatColumns.value = formatArray(v, props.valueKey, props.labelKey);
    },
    {
      deep: true,
      immediate: true,
    },
  );

  // watch(
  //   () => selectedValue.value,
  //   (v) => {
  //     emit('update:modelValue', v);
  //   },
  // );

  /**
   * 行点击事件
   * @param row 行数据
   */
  function handleRowClick(row: ColumnItem, index: number) {
    const { valueKey, multipleSelect, reverseSelect, immediateChange } = props;
    const selected = hasSelected(row);
    const value = row[valueKey];
    if (!multipleSelect) {
      if (reverseSelect && selected) {
        selectedValue.value = '';
      } else {
        selectedValue.value = value;
      }
    } else {
      if (!isArray(selectedValue.value)) {
        selectedValue.value = [selectedValue.value];
      }
      if (reverseSelect && selected) {
        selectedValue.value = selectedValue.value.filter((m) => m !== value);
      } else {
        selectedValue.value = [...selectedValue.value, value];
      }
    }
    // 立即触发
    if (immediateChange) {
      emit('update:modelValue', selectedValue.value);
    }
    // 触发事件
    emit('click', { row, index, value: selectedValue.value });
  }

  /**
   * 是否已选中
   * @param row 行数据
   */
  function hasSelected(row: ColumnItem) {
    const { valueKey } = props;
    let flag = false;
    const value = selectedValue.value;
    if (isArray(value)) {
      flag = value.filter((m) => m === row[valueKey])?.length > 0;
    } else {
      flag = value === row[valueKey];
    }
    return flag;
  }

  /** 获取选中项 */
  function getSelects() {
    const { valueKey, multipleSelect } = props;
    let values = selectedValue.value;
    if (!isArray(values)) {
      values = [values];
    }
    const selects = formatColumns.value.filter(
      (m) => values.filter((v) => v === m[valueKey])?.length > 0,
    );
    if (!multipleSelect) {
      return selects[0];
    }
    return selects;
  }

  /** 获取选中值 */
  function getValues() {
    const { multipleSelect } = props;
    let values = selectedValue.value;
    if (!isArray(values)) {
      values = [values];
    }
    if (!multipleSelect) {
      return values[0];
    }
    return values;
  }

  /** 获取选中项的label */
  function getLabels() {
    const { labelKey, multipleSelect } = props;
    let values = selectedValue.value;
    if (!isArray(values)) {
      values = [values];
    }
    const labels = formatColumns.value
      .filter((m) => values.filter((v) => v === m[labelKey])?.length > 0)
      .map((p) => p[labelKey]);
    if (!multipleSelect) {
      return labels[0];
    }
    return labels;
  }

  /** 获取列数据 */
  function getColumnsData() {
    return deepClone(formatColumns.value);
  }

  /** 用于重置列数据为指定列数据 */
  function resetColumns(
    columns: (string | number | string[] | number[] | ColumnItem | ColumnItem[])[],
  ) {
    if (isArray(columns) && columns.length) {
      formatColumns.value = formatArray(columns, props.valueKey, props.labelKey);
    }
  }

  defineExpose<PickerViewExpose>({
    getSelects,
    getValues,
    getColumnsData,
    getLabels,
    resetColumns,
  });
</script>
<style lang="scss" scoped>
  @import 'wot-design-uni/components/wd-picker-view/index';

  .wd-picker-view {
    padding: unset;
  }
  /* 单格图标 */
  .ea-data-picker-view-cell-icon {
    box-sizing: border-box;
    display: block;
    align-items: center;
    width: 38rpx;
    height: 38rpx;
    margin-right: 20rpx;
    color: $-color-theme;
    background-size: cover;
  }
</style>
